<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\School;
use app\admin\model\Grade;
use app\admin\model\Clazz;
use app\admin\model\Student;
use Carbon\Carbon;

/**
 * 班级管理-服务类
 * @author 牧羊人
 * @since: 2024/10/09
 * Class ClazzService
 * @package app\admin\service
 */
class ClazzService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new Clazz();
        // 解析Token获取用户ID
        $token = request()->header("Authorization");
        $token = str_replace("Bearer ", null, $token);
        $jwt = new \Jwt();
        $this->userId = $jwt->verifyToken($token);
    }
	
	/**
     * 获取数据列表
     * @return array
     * @since 2024/10/09
     * @author 牧羊人
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];
		
	    // 所属组织
        $organization = isset($param['organization']) ? (int)$param['organization'] : '';
        if ($organization) {
            $map[] = ['organization', '=', $organization];
        }
        $sid = getSchooleId($this->userId);
        if ($sid) {
            $map[] = ['organization', '=', $sid];
        }
        // 所属年级
        $grade = isset($param['grade']) ? (int)$param['grade'] : '';
        if ($grade) {
            $map[] = ['grade', '=', $grade];
        }
        
	    // 班级名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }
		
	    // 状态
        $status = isset($param['status']) ? (int)$param['status'] : 0;
        if ($status) {
            $map[] = ['status', '=', $status];
        }

        $data = $this->getList2($map);

        $classIds = array_column($data['data'], 'id');
        $logRecord = db('classlog')
            ->whereIn('class_id', $classIds)
            ->group('class_id')
            ->field('count(id) total, class_id')
            ->select();
        $logRecord = array_column($logRecord, 'total', 'class_id');
        foreach ($data['data'] as &$val) {
            $val['log_record'] = $logRecord[$val['id']] ?? 0;
        }
        return $data;
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function getList2()
    {
        // 初始化变量
        $map = [];
        $sort = 'sort desc,id desc';
        $is_sql = 0;

        // 获取参数
        $argList = func_get_args();
        if (!empty($argList)) {
            // 查询条件
            $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
            // 排序
            $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'sort desc,id desc';
            // 是否打印SQL
            $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        }

        // 常规查询条件
        $param = request()->param();
        if ($param) {
            // 筛选名称
            if (isset($param['name']) && $param['name']) {
                $map[] = ['name', 'like', "%{$param['name']}%"];
            }

            // 筛选标题
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 筛选类型
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }

            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }

            // 手机号码
            if (isset($param['mobile']) && $param['mobile']) {
                $map[] = ['mobile', '=', $param['mobile']];
            }
        }

        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $teacher = getTeacher($this->userId);
        if($teacher){
            $result = $this->model->where($map)  ->where('find_in_set(' .$this->userId. ',teacher) ')->order($sort)->page(PAGE, PERPAGE)->column("id");
        }else{
            $result = $this->model->where($map)->order($sort)->page(PAGE, PERPAGE)->column("id");
        }


        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val);
                $list[] = $info;
            }
        }
        $teacher = getTeacher($this->userId);
        if($teacher){
            //获取数据总数
            $count = $this->model->where($map)->where('find_in_set(' .$this->userId. ',teacher) ')->count();
        }else{
            //获取数据总数
            $count = $this->model->where($map)->count();
        }

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }


    /**
     * 添加或编辑
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function edit()
    {
        // 获取参数
        $argList = func_get_args();
        // 查询条件
        $data = isset($argList[0]) ? $argList[0] : [];
        // 是否打印SQL
        $is_sql = isset($argList[1]) ? $argList[1] : false;
        if (!$data) {
            $data = request()->param();
        }
        $data['teacher'] = implode(',', $data['teacher']);
        $error = '';
        $rowId = $this->model->edit($data, $error, $is_sql);
        if ($rowId) {
            return message();
        }
        return message($error, false);
    }

    /**
     * 获取班级列表
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getClazzList()
    {
        $param = request()->param();
        $where = [];
        $where['mark'] = 1;
        $list = [];
        $sid = getSchooleId($this->userId);
        if ($sid) {
            $where['organization'] = $sid;
        }
        $t = getTeacher($this->userId);
        if($t){
            
            $list = $this->model->where($where)->where('id','in',getClassIds($this->userId))->select()->toArray();
        }else{
            if (isset($param['gid'])&& $param['gid']>0) {
                $where['grade'] = $param['gid'];
                $list = $this->model->where($where)->select()->toArray();
            }else{
                $list = $this->model->where($where)->select()->toArray();
            }
        }


       
        return message("操作成功", true, $list);
    }

    /**
     * 获取树形列表
     * @return mixed
     */
    public function getCatetreeList()
    {
        $sid = getSchooleId($this->userId);
        if($sid){
            $sclist = School::where(['mark'=>1])
                ->field('id,name')
                ->where('id',$sid)
                ->select()->toArray();
        }else{
            $sclist = School::where(['mark'=>1])
                ->field('id,name')
                ->select()->toArray();
        }
        $data = [];
        $index = 0;
        foreach ($sclist as &$value1) {
            $index++;
            $value1['pid'] = 0;
            $value1['index'] = $index;
            $gradelist = Grade::where(['organization'=>$value1['id'],'mark'=>1])->field('id,name')->select()->toArray();
            if (count($gradelist)>0) {
                unset($value1['id']);
            }
            $data[] = $value1;
            foreach ($gradelist as &$value2) {
                $index++;
                $value2['pid'] = $value1['index'];
                $value2['index'] = $index;
                $t = getTeacher($this->userId);
                if($t){
                    $ids = getClassIds($this->userId);
                    $clazzlist = Clazz::where(['grade'=>$value2['id'],'mark'=>1])->where('id','in',$ids)
                        ->field('id,name')->select()->toArray();
                }else{
                    $clazzlist = Clazz::where(['grade'=>$value2['id'],'mark'=>1])
                        ->field('id,name')->select()->toArray();
                }

                if (count($clazzlist)>0) {
                    unset($value2['id']);
                }
                $data[] = $value2;
                foreach ($clazzlist as &$value3) {
                    $index++;
                    $value3['pid'] = $value2['index'];
                    $value3['index'] = $index;
                    $value3['banji'] = true;
                    $data[] = $value3;
                }
                unset($value3);
            }
            unset($value2);
        }
        unset($value1);
        return message("操作成功", true, $data);
    }

    public function classLog()
    {
        $param = request()->param();
        if (empty($param['date'])) {
            $carbon = Carbon::now()->startOfDay();
        } else {
            $carbon = Carbon::createFromTimestamp(strtotime($param['date']))->startOfDay();
        }
        $param['date'] = [
            $carbon->copy()->timestamp,
            $carbon->copy()->endOfDay()->timestamp
        ];
        $data  = db('classlog')
            ->where('class_id', $param['class_id'])
            ->field('student_id, create_time')
            ->whereBetween('create_time', $param['date'])
            ->when(
                !empty($param['keyword']),
                function ($query) use ($param) {
                    $query->whereExists(
                        function ($query) use ($param) {
                            $query->name('student')
                                ->field('1')
                                ->whereRaw('think_classlog.student_id = think_student.id')
                                ->where(
                                    function ($query) use ($param) {
                                        $query->whereOr('id_card', 'like', '%' . $param['keyword'] . '%')
                                            ->whereOr('name', 'like', '%' . $param['keyword'] . '%');
                                    }
                                );
                        }
                    );
                }
            )
            ->paginate()
            ->each(
                function ($item) {
                    $student = (new Student())->getInfo($item['student_id']);
                    $item['create_time'] = date('Y-m-d', $item['create_time']);
                    return array_merge($student, $item);
                }
            );

        return [
            'msg'   => '操作成功',
            'code'  => 0,
            'data'  => $data->items(),
            'count' => $data->total()
        ];
    }

    public function classLogMonth()
    {
        $param = request()->param();
        if (empty($param['date'])) {
            $carbon = Carbon::now()->firstOfMonth();
        } else {
            $carbon = Carbon::createFromTimestamp(strtotime($param['date']))->firstOfMonth();
        }
        $param['date'] = [
            $carbon->copy()->timestamp,
            $carbon->copy()->endOfMonth()->timestamp
        ];
        $data = db('classlog')
            ->where('class_id', $param['class_id'])
            ->field('student_id, count(id) total, create_time')
            ->group('student_id')
            ->whereBetween('create_time', $param['date'])
            ->when(
                !empty($param['keyword']),
                function ($query) use ($param) {
                    $query->whereExists(
                        function ($query) use ($param) {
                            $query->name('student')
                                ->field('1')
                                ->whereRaw('think_classlog.student_id = think_student.id')
                                ->where(
                                    function ($query) use ($param) {
                                        $query->whereOr('id_card', 'like', '%' . $param['keyword'] . '%')
                                            ->whereOr('name', 'like', '%' . $param['keyword'] . '%');
                                    }
                                );
                        }
                    );
                }
            )
            ->paginate()
            ->each(function ($item) {
                $student = (new Student())->getInfo($item['student_id']);
                $item['create_time'] = date('Y-m', $item['create_time']);
                return array_merge($student, $item);
            });
        return [
            'msg' => '操作成功',
            'code' => 0,
            'data' => $data->items(),
            'count' => $data->total()
        ];
    }
}